;
(function() {
  new Vue({
    el: '#template-edit-preview',
    data: {
      templateId: hlUrlUtil.GetQueryString('templateId'),
      data: null,
      pageStyle: {},
      templateValue: [],
      headPerData: [],
      footerPerData: [],
      tbTitleLength: 0,
      tbHead: [],
      tbContent: [],
      isShowWatermarkLayer: false,
      positionList: [{
          'name': '左上'
        },
        {
          'name': '上中'
        },
        {
          'name': '右上'
        },
        {
          'name': '左中'
        },
        {
          'name': '正中'
        },
        {
          'name': '右中'
        },
        {
          'name': '左下'
        },
        {
          'name': '下中'
        },
        {
          'name': '右下'
        }
      ],
      marginList: [{
          'name': '左',
          'value': ''
        },
        {
          'name': '上',
          'value': ''
        },
      ],
      watermarkPosition: '左上',
      watermarkBtn: '上传图片',
      watermarkUrl: null,
      imageWidth: null,
      imageHeight: null,
      watermarkData: [],
      watermarkStyle: [],
      opacityValue: 100,
      isEditWatermark: false,
      watermarkIndex: 0,
      moduleName: null,
    },
    filters: {
      formatUndefined: function(item) {
        if (!item && item != 0) return '--'
        return item
      }
    },
    methods: {
      getTemplateName() {
        var self = this;
        self.getTemplateVal()
        hlhttp.get({
          url:'bill/print_template',
          data:{'template_id':self.templateId},
          success:function(data){
              self.data = data;
              // 模版名
              self.moduleName = data.name;
              // 页边距
              var pageData = data.page[0];
              self.pageStyle = {
                'paddingLeft': pageData ? pageData.eleMarginLeft + 'px' : '0px',
                'paddingRight': pageData ? pageData.eleMarginRight + 'px' : '0px',
                'paddingTop': pageData ? pageData.eleMarginTop + 'px' : '0px',
                'paddingBottom': pageData ? pageData.eleMarginBottom + 'px' : '0px'
              }
              // 水印图片
              if (data.image) {
                data.image.forEach((el, i) => {
                  var obj = {
                    'url': el.eleValue,
                    'width': el.eleWidth + '',
                    'height': el.eleHeight + '',
                    'opacity': el.eleOpacity + '',
                    'left': el.eleMarginLeft + '',
                    'right': el.eleMarginRight + '',
                    'top': el.eleMarginTop + '',
                    'bottom': el.eleMarginBottom + ''
                  }
                  var objStyle = {
                    'url': el.eleValue,
                    'width': el.eleWidth + 'px',
                    'height': el.eleHeight + 'px',
                    'opacity': el.eleOpacity + 'px',
                    'left': el.eleMarginLeft ? el.eleMarginLeft + 'px' : null,
                    'right': el.eleMarginRight ? el.eleMarginRight + 'px' : null,
                    'top': el.eleMarginTop ? el.eleMarginTop + 'px' : null,
                    'bottom': el.eleMarginBottom ? el.eleMarginBottom + 'px' : null
                  }
                  self.watermarkData.push(obj)
                  self.watermarkStyle.push(objStyle)
                })
              }

              // 头部
              var headData = []
              if (data.head.length && data.head != '#') headData = hlArrayUtil.splitInToTwoimensionalArray(data.head, 3);
              // 去除掉空格占位符
              var tmpHeadArr = [];
              headData.forEach((el, i) => {
                var tmpArr = [];
                var blankNum = 0;

                el.forEach((item, index) => {
                  if (item.eleType === 'sys') item['eleVal'] = self.matchTemplateVal(item.eleValue)
                  if (item.eleType === 'ph') blankNum++;
                })

                // 该循环用来分配每个要展示的模块的所占比例
                el.forEach((item, index) => {
                  if (blankNum == 0) item['width'] = 'w33'
                  if (blankNum == 1 && item.eleType == 'ph') item['width'] = 'w00'
                  if (blankNum == 1 && item.eleType != 'ph') item['width'] = 'w50'
                  if (blankNum == 2 && item.eleType == 'ph') item['width'] = 'w00'
                  if (blankNum == 2 && item.eleType != 'ph') item['width'] = 'w100'
                  if (blankNum == 3) item['width'] = 'w33'
                  tmpArr.push(item)
                })
                tmpHeadArr.push(tmpArr)
              })
              self.headPerData = tmpHeadArr;
              // 收费表格
              var tmpContentArr = data.content;
              self.tbTitleLength = 0;
              data.content.forEach((el, i) => {
                if (el.eleShow == 'Y') self.tbTitleLength++;
              })
              self.tbHead = tmpContentArr;
              var allTbContent = self.templateValue.expenses;
              var tmpTbContent = [];
              var payedTotalPrice = 0,
                receiveTotalPrice = 0,
                totalPrice = 0,
                receiveOriginalTotalPrice = 0,
                receiveDiscountTotalPrice = 0;

              allTbContent.forEach((el, i) => {
                var arr = [];
                self.tbHead.forEach((item, index) => {
                  arr.push({
                    'value': el[item.eleValue],
                    'eleShow': item.eleShow
                  })

                  // 合计中要显示总金额
                  if (item.eleValue == 'amountReceive') totalPrice = totalPrice + Number(el.amountReceive)
                  if (item.eleValue == 'amountPayed') payedTotalPrice = payedTotalPrice + Number(el.amountPayed)
                  if (item.eleValue == 'amountTpay') receiveTotalPrice = receiveTotalPrice + Number(el.amountTpay)
                  if (item.eleValue == 'amountReceiveOriginal') receiveOriginalTotalPrice = receiveOriginalTotalPrice + Number(el.amountReceiveOriginal)
                  if (item.eleValue == 'amountReceiveDiscount') receiveDiscountTotalPrice = receiveDiscountTotalPrice + Number(el.amountReceiveDiscount)

                })
                tmpTbContent.push(arr)
              })
              // 新增一行计算总价钱
              var lastArr = [];
              self.tbHead.forEach((item, index) => {
                let eleValue = item.eleValue, eleValueArr = ['name','amountReceive','amountPayed','amountTpay','amountReceiveOriginal','amountReceiveDiscount']

                if(eleValueArr.indexOf(eleValue) == -1){
                  lastArr.push({ 'value': '', 'eleShow': item.eleShow })
                }
                // 费项那一列新增一行显示合计
                if (eleValue == 'name') lastArr.push({
                  'value': '合计',
                  'eleShow': item.eleShow
                })
                if (eleValue == 'amountReceive') lastArr.push({
                  'value': totalPrice.toFixed(2),
                  'eleShow': item.eleShow
                })
                if (eleValue == 'amountPayed') lastArr.push({
                  'value': payedTotalPrice.toFixed(2),
                  'eleShow': item.eleShow
                })
                if (eleValue == 'amountTpay') lastArr.push({
                  'value': receiveTotalPrice.toFixed(2),
                  'eleShow': item.eleShow
                })
                if (eleValue == 'amountReceiveOriginal') lastArr.push({
                  'value': receiveOriginalTotalPrice.toFixed(2),
                  'eleShow': item.eleShow
                })
                if (eleValue == 'amountReceiveDiscount') lastArr.push({
                  'value': receiveDiscountTotalPrice.toFixed(2),
                  'eleShow': item.eleShow
                })
              })
              tmpTbContent.push(lastArr)
              self.tbContent = tmpTbContent;

              // 尾部
              var footerData = [];
              if (data.tail.length && data.tail != '#') footerData = hlArrayUtil.splitInToTwoimensionalArray(data.tail, 3);
              // 去除掉空格占位符
              var tmpFooterArr = [];
              footerData.forEach((el, i) => {
                var tmpArr = [];
                var blankNum = 0;

                el.forEach((item, index) => {
                  if (item.eleType === 'sys') item['eleVal'] = self.matchTemplateVal(item.eleValue)
                  if (item.eleType === 'ph') blankNum++;
                })

                // 该循环用来分配每个要展示的模块的所占比例
                el.forEach((item, index) => {
                  if (blankNum == 0) item['width'] = 'w33'
                  if (blankNum == 1 && item.eleType == 'ph') item['width'] = 'w00'
                  if (blankNum == 1 && item.eleType != 'ph') item['width'] = 'w50'
                  if (blankNum == 2 && item.eleType == 'ph') item['width'] = 'w00'
                  if (blankNum == 2 && item.eleType != 'ph') item['width'] = 'w100'
                  if (blankNum == 3) item['width'] = 'w33'
                  tmpArr.push(item)
                })
                tmpFooterArr.push(tmpArr)

              })
              self.footerPerData = tmpFooterArr;
          }
        })
      },

      getTemplateVal() {
        var self = this;

        // 账单模版预览模拟数据
        var elementVal = {
          'projectName': '账单模版测试项目',
          'contractMCode': 'C201712130160',
          'contractCCode': '账单模版测试合同编号',
          'contractName': '账单模版测试合同',
          'contractSignDate': '2017-12-12',
          'rentBeginDate': '2017-12-13',
          'rentEndDate': '2020-12-12',
          'rentDuration': '2017-12-13 到 2020-12-12',
          'customerName': '账单模版测试客户',
          'rentResources': '账单模版测试项目-金刚楼-3楼-A001、A002',
          'rentUnitAcreage': '20',
          'rentWpCount': '0',
          'rentStCount': '2',
          'billNo': 'ar201712190043',
          'billDuration': '2017-12-13 至 2018-12-12',
          'currentDate': '2018-07-08',
          'currentTime': '2018-07-08 10:35',
          'currentOperator': '管理员',
          'bankName': '中国银行',
          'bankAccount': '6888 8888 8888 8888',
          'accountName': '1号楼资管云'
        }
        var expenses = [{
            'expenseType': 'R',
            'name': '固定租金',
            'paymentDeadline': '2017-12-23',
            'beginDate': '2017-12-13',
            'endDate': '2018-12-12',
            'expenseDuration': '2017-12-13 至 2018-12-12',
            'priceDay': '100',
            'rentPrice': '123',
            'priceMonth': '590',
            'rentUnitAcreage': '500',
            'amountTpay': '10000.00',
            'amountPayed': '6000.00',
            'amountReceive': '12000.00',
            'paymentState': 'WP',
            'amountReceiveOriginal': '18000',
            'amountReceiveDiscount': '10000',
          },
          {
            'expenseType': '2',
            'name': '水费',
            'paymentDeadline': '2017-12-23',
            'beginDate': '2017-12-13',
            'endDate': '2018-12-12',
            'expenseDuration': '2017-12-13 至 2018-12-12',
            'priceDay': '20',
            'rentPrice': '123',
            'priceMonth': '560',
            'rentUnitAcreage': '100',
            'amountTpay': '600.00',
            'amountPayed': '10.00',
            'amountReceive': '700.00',
            'paymentState': 'WP',
            'amountReceiveOriginal': '600',
            'amountReceiveDiscount': '500',
          },
          {
            'expenseType': 'R',
            'name': '电费',
            'paymentDeadline': '2017-12-23',
            'beginDate': '2017-12-13',
            'endDate': '2018-12-12',
            'rentPrice': '123',
            'expenseDuration': '2017-12-13 至 2018-12-12',
            'priceDay': '30',
            'priceMonth': '590',
            'rentUnitAcreage': '200',
            'amountTpay': '800.00',
            'amountPayed': '200.00',
            'amountReceive': '900.00',
            'paymentState': 'WP',
            'amountReceiveOriginal': '800',
            'amountReceiveDiscount': '600',
          }
        ]

        self.templateValue = {
          'element_val': elementVal,
          'expenses': expenses
        }
      },

      matchTemplateVal(code) {
        var result;
        var elementVal = this.templateValue.element_val;

        switch (code) {
          case 'projectName':
            result = elementVal.projectName
            break;
          case 'contractMCode':
            result = elementVal.contractMCode
            break;
          case 'contractCCode':
            result = elementVal.contractCCode
            break;
          case 'contractName':
            result = elementVal.contractName
            break;
          case 'contractSignDate':
            result = elementVal.contractSignDate
            break;
          case 'rentBeginDate':
            result = elementVal.rentBeginDate
            break;
          case 'rentEndDate':
            result = elementVal.rentEndDate
            break;
          case 'rentDuration':
            result = elementVal.rentDuration
            break;
          case 'customerName':
            result = elementVal.customerName
            break;
          case 'rentResources':
            result = elementVal.rentResources
            break;
          case 'rentUnitAcreage':
            result = elementVal.rentUnitAcreage
            break;
          case 'rentWpCount':
            result = elementVal.rentWpCount
            break;
          case 'rentStCount':
            result = elementVal.rentStCount
            break;
          case 'billNo':
            result = elementVal.billNo
            break;
          case 'billDuration':
            result = elementVal.billDuration
            break;
          case 'currentDate':
            result = elementVal.currentDate
            break;
          case 'currentTime':
            result = elementVal.currentTime
            break;
          case 'currentOperator':
            result = elementVal.currentOperator
            break;
          case 'bankName':
            result = elementVal.bankName
            break;
          case 'bankAccount':
            result = elementVal.bankAccount
            break;
          case 'accountName':
            result = elementVal.accountName
            break;
          default:
        }

        return result;
      },

      editTemplate() {
        var self = this;
        hlUrlUtil.goTo('templateEdit', {'templateId':self.templateId,ddtab:true}, false)
      },

      showWatermarkLayer() {
        this.isEditWatermark = false;
        this.isShowWatermarkLayer = true;
        this.watermarkBtn = '上传图片';
        this.watermarkUrl = null;
        this.imageWidth = null;
        this.imageHeight = null;
        this.marginList = [{
          'name': '左',
          'value': ''
        }, {
          'name': '上',
          'value': ''
        }];
        this.watermarkPosition = '左上';
        this.opacityValue = 100;
      },
      closeWatermarkLayer() {
        this.isShowWatermarkLayer = false;
      },
      saveTemplate() {
        // 头部
        var self = this;
        var data = JSON.parse(JSON.stringify(self.data));
        var head = [],
          content = [],
          tail = [],
          image = [],
          page = [];

        var pageObj = {
          'ele_id': data.page.eleId,
          'ele_name': '#',
          'ele_disp_name': '#',
          'ele_type': 'page',
          'ele_value': '#',
          'ele_block': 'page',
          'ele_position': '#',
          'ele_height': '#',
          'ele_width': '#',
          'ele_size': '#',
          'ele_margin_left': data.page[0].eleMarginLeft + '',
          'ele_margin_right': data.page[0].eleMarginRight + '',
          'ele_margin_top': data.page[0].eleMarginTop + '',
          'ele_margin_bottom': data.page[0].eleMarginBottom + '',
          'ele_metric': '#',
          'ele_opacity': '#',
          'ele_order': '#',
          'ele_show': '#'
        }
        page.push(pageObj)

        data.content.forEach((el, i) => {
          var obj = {
            'ele_block': 'content',
            'ele_id': el.eleId,
            'ele_name': el.eleName,
            'ele_disp_name': el.eleDispName,
            'ele_show': el.eleShow,
            'ele_value': el.eleValue,
            'ele_order': el.eleOrder,
            'ele_type': 'col'
          }
          content.push(obj)
        })

        data.head.forEach((el, i) => {
          var obj = {
            'ele_id': el.eleId,
            'ele_name': el.eleName,
            'ele_disp_name': el.eleDispName ? el.eleDispName : '#',
            'ele_type': el.eleType,
            'ele_value': el.eleValue ? el.eleValue : '#',
            'ele_block': el.eleBlock,
            'ele_position': el.elePosition,
            'ele_height': '#',
            'ele_width': '#',
            'ele_size': el.eleSize ? el.eleSize : '#',
            'ele_margin_left': '#',
            'ele_margin_right': '#',
            'ele_margin_top': '#',
            'ele_margin_bottom': '#',
            'ele_metric': el.eleMetric ? el.eleMetric : '#',
            'ele_opacity': '#',
            'ele_order': el.eleOrder ? el.eleOrder : '#',
            'ele_show': '#'
          }
          head.push(obj)
        })
        data.tail.forEach((el, i) => {
          var obj = {
            'ele_id': el.eleId,
            'ele_name': el.eleName,
            'ele_disp_name': el.eleDispName ? el.eleDispName : '#',
            'ele_type': el.eleType,
            'ele_value': el.eleValue ? el.eleValue : '#',
            'ele_block': el.eleBlock,
            'ele_position': el.elePosition,
            'ele_height': '#',
            'ele_width': '#',
            'ele_size': el.eleSize ? el.eleSize : '#',
            'ele_margin_left': '#',
            'ele_margin_right': '#',
            'ele_margin_top': '#',
            'ele_margin_bottom': '#',
            'ele_metric': el.eleMetric ? el.eleMetric : '#',
            'ele_opacity': '#',
            'ele_order': el.eleOrder ? el.eleOrder : '#',
            'ele_show': '#'
          }
          tail.push(obj)
        })
        self.watermarkData.forEach((el, i) => {
          var obj = {
            'ele_id': el.eleId ? el.eleId : '#',
            'ele_name': '#',
            'ele_disp_name': '#',
            'ele_type': 'img',
            'ele_value': el.url,
            'ele_block': 'image',
            'ele_position': '#',
            'ele_height': el.height,
            'ele_width': el.width,
            'ele_size': '#',
            'ele_margin_left': el.left ? el.left + '' : '#',
            'ele_margin_right': el.right ? el.right + '' : '#',
            'ele_margin_top': el.top ? el.top + '' : '#',
            'ele_margin_bottom': el.bottom + '' ? el.bottom + '' : '#',
            'ele_metric': 'px',
            'ele_opacity': el.opacity + '',
            'ele_order': '#',
            'ele_show': '#'
          }
          image.push(obj)
        })

        var subData = {
          id:self.templateId,
          name: data.name,
          page: JSON.stringify(page),
          image: image.length ? JSON.stringify(image) : '#',
          head: head.length ? JSON.stringify(head) : '#',
          content: JSON.stringify(content),
          tail: tail.length ? JSON.stringify(tail) : '#'
        }

        hlhttp.put({
          url: 'bill/print_template',
          data: { 'print_template': JSON.stringify(subData) },
          success: function(data) {
            hl.toast('保存成功')
            hlUrlUtil.goTo('templateDetails',{'templateId':self.templateId,ddtab:true},true)
          }
        })

      },
      uploadWatermark() {
        var self = this;
        imgupload('#upload-watermark', uploadUrl, function(src) {
          self.watermarkUrl = src.json.url;
          self.watermarkBtn = '重新上传'
        })
      },
      confirmAddWatermark() {
        const getWatermarkData = () => {
          const getPositionValue = (data) => {
            var direction = data.name,
              res;
            switch (direction) {
              case '上':
                res = {
                  'direction': 'top',
                  'value': data.value
                }
                break;
              case '下':
                res = {
                  'direction': 'bottom',
                  'value': data.value
                }
                break;
              case '左':
                res = {
                  'direction': 'left',
                  'value': data.value
                }
                break;
              case '右':
                res = {
                  'direction': 'right',
                  'value': data.value
                }
                break;
              default:
            }
            return res;
          }

          const pos1 = getPositionValue(this.marginList[0]);
          const direction1 = pos1.direction
          const value1 = pos1.value;
          const pos2 = getPositionValue(this.marginList[1]);
          const direction2 = pos2.direction;
          const value2 = pos2.value;

          var obj = {
            'url': this.watermarkUrl,
            'width': this.imageWidth,
            'height': this.imageHeight,
            'opacity': this.opacityValue / 100
          }
          var styleObj = {
            'width': this.imageWidth + 'px',
            'height': this.imageHeight + 'px',
            'opacity': this.opacityValue / 100
          }
          obj[direction1] = value1;
          obj[direction2] = value2;
          styleObj[direction1] = value1 + 'px';
          styleObj[direction2] = value2 + 'px';
          // 编辑水印
          if (this.isEditWatermark == true) {
            this.$set(this.watermarkData, this.watermarkIndex, obj)
            this.$set(this.watermarkStyle, this.watermarkIndex, styleObj)
          }
          // 新增水印
          if (this.isEditWatermark == false) {
            this.watermarkStyle.push(styleObj)
            this.watermarkData.push(obj)
          }
        }

        if (this.validate()) {
          getWatermarkData()
          this.isShowWatermarkLayer = false;
        }
      },
      selectPosition(position) {
        this.watermarkPosition = position;
        if (!this.imageWidth || !this.imageHeight) hl.toast('请填写图片尺寸')
        const rowCenter = document.querySelector('.tmp-preview-wrap').offsetWidth / 2 - this.imageWidth / 2;
        const columnCenter = document.querySelector('.tmp-preview-wrap').offsetHeight / 2 - this.imageHeight / 2;
        // 位置定位边距
        if (position == '左上') this.marginList = [{
          'name': '左',
          'value': null
        }, {
          'name': '上',
          'value': null
        }]
        if (position == '上中') this.marginList = [{
          'name': '左',
          'value': rowCenter
        }, {
          'name': '上',
          'value': null
        }]
        if (position == '右上') this.marginList = [{
          'name': '右',
          'value': null
        }, {
          'name': '上',
          'value': null
        }]

        if (position == '左中') this.marginList = [{
          'name': '左',
          'value': null
        }, {
          'name': '上',
          'value': columnCenter
        }]
        if (position == '正中') this.marginList = [{
          'name': '左',
          'value': rowCenter
        }, {
          'name': '上',
          'value': columnCenter
        }]
        if (position == '右中') this.marginList = [{
          'name': '右',
          'value': null
        }, {
          'name': '上',
          'value': columnCenter
        }]

        if (position == '左下') this.marginList = [{
          'name': '左',
          'value': null
        }, {
          'name': '下',
          'value': columnCenter
        }]
        if (position == '下中') this.marginList = [{
          'name': '左',
          'value': rowCenter
        }, {
          'name': '下',
          'value': null
        }]
        if (position == '右下') this.marginList = [{
          'name': '右',
          'value': null
        }, {
          'name': '下',
          'value': null
        }]

      },
      editWatermark(index) {
        var self = this;

        self.isShowWatermarkLayer = true;
        self.watermarkIndex = index;
        self.isEditWatermark = true;
        self.watermarkUrl = self.watermarkData[index]['url'];
        self.imageWidth = self.watermarkData[index]['width'];
        self.imageHeight = self.watermarkData[index]['height'];
        self.opacityValue = self.watermarkData[index]['opacity'] * 100;

        var tmpArr = [];
        if (self.watermarkStyle[index]['left']) tmpArr.push({
          'name': '左',
          'value': parseFloat(self.watermarkStyle[index]['left'])
        })
        if (self.watermarkStyle[index]['top']) tmpArr.push({
          'name': '上',
          'value': parseFloat(self.watermarkStyle[index]['top'])
        })
        if (self.watermarkStyle[index]['right']) tmpArr.push({
          'name': '右',
          'value': parseFloat(self.watermarkStyle[index]['right'])
        })
        if (self.watermarkStyle[index]['bottom']) tmpArr.push({
          'name': '下',
          'value': parseFloat(self.watermarkStyle[index]['bottom'])
        })

        self.marginList = tmpArr;
      },
      deleteWatermark(index) {
        this.watermarkData.splice(index, 1)
        this.watermarkStyle.splice(index, 1)
      },
      validate() {
        if (!this.watermarkUrl) {
          hl.toast('请上传图片')
          return false;
        }
        if (!this.imageWidth || !this.imageHeight) {
          hl.toast('请填写图片尺寸')
          return false;
        }
        if (!this.marginList[0]['value'] || !this.marginList[1]['value']) {
          hl.toast('请填写图片边距')
          return false;
        }
        return true
      },
      initSlider(curValue) {
        const change = (data) => {
          this.opacityValue = $(data).attr('value');
          const left = $(data).attr('value') * 4 - 18;
          $('.range-value-wrap').css('left', left);
        }
        $('#slideIpt').rangeSlider({
          curValue: curValue,
          callback: change
        })
      }
    },
    created:function(){
      this.getTemplateVal()
    },
    mounted: function() {
      this.getTemplateName()
      this.uploadWatermark()
      this.initSlider(100)
      $('#upload-watermark').trigger('click')
    }
  })
}())
